//
//  UserAccount.swift
//  SinaWeibo
//
//  Created by 周小伟 on 16/8/24.
//  Copyright © 2016年 周小伟. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
    var access_token:String?
    //access_token 生命周期，单位是秒 开发者过期时间5年，普通用户3天
    var expires_in:NSTimeInterval = 0{
        didSet{
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var uid:String?
    var avatar_large:String?
    var name:String?
    var expires_date:NSDate?
    init(dict:[String:AnyObject]){
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = (aDecoder.decodeObjectForKey("expires_in") as? NSTimeInterval)!
        uid = aDecoder.decodeObjectForKey("uid") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    override var description: String{
        let keys = ["access_token","expires_in","uid","avatar_large","name","expires_date"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
    func saveAccount(){
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        print(path)
    }
    
    class func loadAccount()->UserAccount?{
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount{
            if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                return account
            }
        }
        return nil
    }
}
